package com.projectxxxxxxxxxx.utils;

public class UnitConverter {
	public enum TemperatureUnit {
		Kelvin, Celsius, Fahrenheit, Rankine
	}

	private final double UnitsFforC = 1.8;
	private final double FreezeF = 32.0;
	private final double FreezeAbsC = 273.15;

	public double ConvertTemperature(double baseValue, TemperatureUnit srcUnit, TemperatureUnit dstUnit) {
		// nothing to do
		if (srcUnit == dstUnit) {
			return baseValue;
		}

		// normalize everything to celsius
		double celsius;
		if (srcUnit == TemperatureUnit.Kelvin) {
			celsius = baseValue - FreezeAbsC;
		} else if (srcUnit == TemperatureUnit.Fahrenheit) {
			celsius = (baseValue - FreezeF) / UnitsFforC;
		} else if (srcUnit == TemperatureUnit.Rankine) {
			celsius = (baseValue / UnitsFforC) - FreezeAbsC;
		} else {
			celsius = baseValue;
		}

		double returnValue;
		// convert out from celsius
		if (dstUnit == TemperatureUnit.Kelvin) {
			returnValue = celsius + FreezeAbsC;
		} else if (dstUnit == TemperatureUnit.Rankine) {
			returnValue = (celsius + FreezeAbsC) * UnitsFforC;
		} else if (dstUnit == TemperatureUnit.Fahrenheit) {
			returnValue = (celsius * UnitsFforC) + FreezeF;
		} else {
			returnValue = celsius;
		}
		// repeating decimals aren't that useful here, we'll take it to 3 places
		return (Math.floor((returnValue * 1000.0) + 0.5)) / 1000.0;

	}
}